const util = require("./utils/util");
const requestUtil = require("./utils/request");
const api = require("./config/api");
const TIM = require("./components/tim/tim-wx");
const timConst = require("./config/const");

App({
  onLaunch: function () {
    //wx.$TIM = TIM.create(timConst.TimOptions);
    // 获取系统状态栏信息
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        this.globalData.screenHeight = e.screenHeight;
        this.globalData.screenWidth = e.screenWidth;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
  },
  onShow: function (o) {
    if (!this.globalData.allowOnShow) {
      return;
    }
    let _this = this;
    // 分享进入小程序则进入这里
    if (o) {
      if (o.scene == 1007 || o.scene == 1008) {
        this.globalData.isHome = true;
      }else if(o.scene == 1000) {
        return;
      }
    }
    wx.checkSession({
      success: () => {
        let openid = wx.getStorageSync('openid');
        if (!openid) {
          _this.login();
          return;
        }
        _this.queryInfoByOpenid(openid);
      },
      fail: () => {
        _this.login();
      }
    });
    this.dictType();
  },

  onHide: function () {
    // 让TIM在此时结束登录
    // let promise = wx.$TIM.logout();
    // promise.then(function (imResponse) {
    //   console.log('退出成功', imResponse.data); // 退出成功
    // }).catch(function (imError) {
    //   console.warn('logout error:', imError);
    // });
  },

  login: function () {
    this.onLogin();
  },

  /**
   * 登录方法
   */
  onLogin: function () {
    let _this = this;
    wx.login({
      async success(res) {
        if (res.code) {
          let loginRes = await requestUtil.request("POST", api.urls.initUserInfo, {
            code: res.code
          });
          if (loginRes.data.code != 0) {
            util.showToast('服务器出错，请联系管理员。', 'none');
            return null;
          }
          _this.globalData.userType = loginRes.data.data.userType;
          if (loginRes.data.data.userInfo.length > 0 && loginRes.data.data.userInfo[0].headImgUrl != null) {
            loginRes.data.data.userInfo[0].headImgUrl = api.picUrl + loginRes.data.data.userInfo[0].headImgUrl
          }
          _this.globalData.customInfo = loginRes.data.data.custInfo != null ? loginRes.data.data.custInfo[0] : null;
          _this.globalData.employeeInfo = loginRes.data.data.userInfo.length > 0 ? loginRes.data.data.userInfo[0] : null;
          _this.checkCardInfo();
          // 设置缓存
          wx.setStorage({
            key: 'openid',
            data: loginRes.data.data.openid
          })
          wx.setStorage({
            key: 'session_key',
            data: loginRes.data.data.session_key
          })
          _this.getLoginCallback();
          _this.getCardCallbak();
        }
      },
      fail(res) {
        util.showToast(err.data.msg);
        console.error("登录失败:", res)
      }
    })
  },

  /**
   * 查询用户数据
   */
  queryInfoByOpenid: async function (openid) {
    let _this = this;
    let res = await requestUtil.request('POST', api.urls.getUserInfo, {
      openid: openid
    });
    if (res.data.code != 0) {
      util.showToast('服务器出错，请联系管理员。', 'none');
      return null;
    }
    _this.globalData.userType = res.data.data.userType;
    if (res.data.data.userInfo.length > 0 && res.data.data.userInfo[0].headImgUrl != null) {
      res.data.data.userInfo[0].headImgUrl = api.picUrl + res.data.data.userInfo[0].headImgUrl
    }
    _this.globalData.customInfo = res.data.data.custInfo.length > 0 ? res.data.data.custInfo[0] : null;
    _this.globalData.employeeInfo = res.data.data.userInfo.length > 0 ? res.data.data.userInfo[0] : null;
    _this.checkCardInfo();
    _this.getLoginCallback();
    _this.getCardCallbak();
  },

  /**
   * 通过分享打开小程序的用户
   */
  shareComeIn: function (o) {
    this.addVisitStorage(o.query.id);
  },

  /**
   * 根据id添加到历史记录缓存里
   * @params id 字符串格式id
   */
  addVisitStorage: function (id) {
    let localUserIds = wx.getStorageSync('userIds');
    if (localUserIds) {
      let arr = localUserIds.split(',');
      if (arr.indexOf(id.toString()) == -1) {
        arr.push(id);
      }
      localUserIds = arr;
    } else {
      localUserIds = id;
    }
    wx.setStorage({
      key: "userIds",
      data: localUserIds.toString()
    });
  },

  /**
   * 添加
   */
  addVisitIds: function () {

  },

  /**
   * CallBack
   */
  getLoginCallback: function () {
    if (this.loginCallback) {
      this.loginCallback();
    }
  },

  /**
   * CallBack
   */
  getCardCallbak: function () {
    if (this.cardCallback) {
      this.cardCallback();
    }
  },

  /**
   * 判断有没有卡片数据
   */
  checkCardInfo: function () {
    if (!util.objIsNull(this.globalData.employeeInfo)) {
      this.globalData.hasCardInfo = true;
      this.globalData.companyId = this.globalData.employeeInfo.companyId;
      if (!util.isNullOrEmpty(this.globalData.employeeInfo.mobile)) {
        this.globalData.hasCardInfoWithPhone = true;
        this.globalData.hasGetPhoneNumber = true;
      } else {
        this.globalData.hasCardInfoWithPhone = false;
        this.globalData.hasGetPhoneNumber = false;
      }
    } else if (!util.objIsNull(this.globalData.customInfo)) {
      this.globalData.hasCardInfo = true;
      this.globalData.companyId = this.globalData.customInfo.companyId;
      if (!util.isNullOrEmpty(this.globalData.customInfo.phone)) {
        this.globalData.hasCardInfoWithPhone = true;
        this.globalData.hasGetPhoneNumber = true;
      } else {
        this.globalData.hasCardInfoWithPhone = false;
        this.globalData.hasGetPhoneNumber = false;
      }
    } else {
      this.globalData.hasCardInfo = false;
      this.globalData.hasCardInfoWithPhone = false;
      this.globalData.hasGetPhoneNumber = false;
    }
  },

  /**
   * 获取用户sig
   */
  getUserSig: async function () {
    let cardInfo = this.globalData.userType == 1 ? this.globalData.employeeInfo : this.globalData.userType == 2 ? this.globalData.customInfo : null;
    if (!cardInfo) {
      return;
    }
    if (util.isNullOrEmpty(cardInfo.id)) {
      return;
    }
    let key = this.globalData.userType == 1 ? 'E' + cardInfo.id : 'C' + cardInfo.id
    let sig = await requestUtil.request("POST", api.urls.getUserSig, {
      key: key
    })
    console.log('sig', sig);
    this.globalData.userSig = sig.data.data.userSig;
    this.globalData.adminSig = sig.data.data.adminSig;
  },
  async dictType() {
    let that = this;
    let res = await requestUtil.request("GET", api.urls.dictType + 'xcx_login_status', null);
    if(parseInt(res.data.data.status) == 0){
        that.globalData.isXcxLogin = true;
    }else {
        that.globalData.isXcxLogin = false;
    }
  },

  globalData: {
    isXcxLogin: null,
    headImg: null,
    phone: '', // 用户的手机号
    pageNo: 1, // 页码
    pageNum: 10, // 每页展示数
    companyId: null,//公司id
    employeeInfo: null, // 员工信息
    customInfo: null, // 顾客信息
    userType: 2, // 用户角色，1 员工，2 顾客（默认）
    hasCardInfo: false, // 是否有卡片信息
    hasGetPhoneNumber: false, // 是否已获取手机号
    hasCardInfoWithPhone: false, // 是否曾绑定过手机号
    allowOnShow: true, // 是否允许进行app.js-->onShow()操作，因为某些方法（例如获取图像）会再次调用页面的onShow方法
  }
})